/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.star.admin.controller;

import com.star.common.CommonUtil;
import com.star.common.RenderModel;
import com.start.model.SessionModel;
import com.start.model.UserModel;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author ngotandieu
 */
public class AdminLoginController extends HttpServlet {
    private static final Logger logger = Logger.getLogger(AdminLoginController.class);
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    private void handle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            processs(req, resp);
        } catch (IOException ex) {
            logger.error("AdminLoginController.handle:" + ex.getMessage(), ex);
        }
    }

    private void processs(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content;
        String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo();
        switch (pathInfo) {
            case "/ajax-do-login":
                content = ajaxDoLogin(req, resp);
                break;
            case "/logout":
                content = ajaxDoLogout(req, resp);
                break;
            default: 
                content = renderLoginPage(req, resp);
        }
        CommonUtil.out(content, resp);
    }
    
    private String renderLoginPage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content = "";
        TemplateDataDictionary dic = TemplateDictionary.create();
        try {
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            
            String r = req.getParameter("r") != null ? req.getParameter("r") : "";
            dic.setVariable("REF", r);
            Template template = RenderModel.getAdminCTemplate("login_page");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminLoginController.renderLoginPage:" + ex.getMessage(), ex);
        }
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
        return content;
    }
    
    private String ajaxDoLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content = "";
        int error = -1;
        String msg = "Đăng nhập không thành công";
        try {
            String u = req.getParameter("u") != null ? req.getParameter("u") : "";
            String p = req.getParameter("p") != null ? req.getParameter("p") : "";
            UserModel userModel = UserModel.getInstance();
            if (!u.equalsIgnoreCase("") && !p.equalsIgnoreCase("")) {
                boolean validateUser = userModel.validateUser(u, p);
                if (validateUser) {
                    error = 0;
                    msg = "Đăng nhập thành công";
                    SessionModel sessionModel = SessionModel.getInstance();
                    sessionModel.setSession(u, req, resp);
                }
            }
            content = CommonUtil.toJSON(error, msg);
        } catch (Exception ex) {
            logger.error("AdminLoginController.renderCheckLogin:" + ex.getMessage(), ex);
        }
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        return content;
    }

    private String ajaxDoLogout(HttpServletRequest req, HttpServletResponse resp) {
        try {
            SessionModel sessionModel = SessionModel.getInstance();
            sessionModel.deleteSession(req, resp);
            resp.sendRedirect("/login");
        } catch (IOException ex) {
            logger.error("AdminLoginController.ajaxDoLogout:" + ex.getMessage(), ex);
        }
        return "";
    }
}

